package cn.coder.jdbc.core;

import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Properties;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class JdbcDataSource implements DataSource {
	private static final Logger logger = LoggerFactory.getLogger(JdbcDataSource.class);

	private ConnectionPool pool;
	private final Properties config;

	public JdbcDataSource(Properties properties) {
		this.config = properties;
	}

	private void createPool() {
		try {
			this.pool = new ConnectionPool(this.config);
		} catch (SQLException e) {
			logger.error("Create connection pool faild", e);
		}
	}

	@Override
	public PrintWriter getLogWriter() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {
		// TODO Auto-generated method stub

	}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {
		// TODO Auto-generated method stub

	}

	@Override
	public int getLoginTimeout() throws SQLException {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Connection getConnection() throws SQLException {
		if (this.pool == null) {
			createPool(); //在使用的时候创建连接池
		}

		final Connection conn = this.pool.getConnection();

		return (Connection) Proxy.newProxyInstance(this.getClass().getClassLoader(),
				new Class<?>[] { Connection.class }, new InvocationHandler() {

					@Override
					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
						// 如果关闭连接，将connection添加到队列
						if ("close".equals(method.getName())) {
							JdbcDataSource.this.pool.releaseConnection(conn);
							return null;
						}
						return method.invoke(conn, args);
					}
				});
	}

	@Override
	public Connection getConnection(String username, String password) throws SQLException {
		return getConnection();
	}

	public void close() {
		if (this.pool != null) {
			this.pool.clear();
			this.pool = null;
		}
	}

}
